import dTalkApi from '../core/dTalkApi';
import storeInfoModel from '../model/storeInfoModel';
import storeRecoderModel from '../model/storeRecoderModel';
import visitMonthPlanModel from '../model/visitMonthPlanModel';
import consumerRecoderModel from '../model/consumerRecoderModel';
import * as moment from 'moment';
import dTalkApiUtil from 'dingtalk-app/dtalk/dTalkApiUtil';
import formDataService from './formDataService';
import emplModel from '../model/empl2Model';
import excelExportModel from '../model/excelExportModel';
import addNewService from '../services/addNewService';

//报表service------统计各种数据
class ReportFormService {
    constructor() {}
      
    //(一)客户拜访达成率---报表
    async getReachConsumerRate(startDate1: string, endDate1: string, character: string, comment: string, leaderId: string) {
        let dateData=await formDataService.getDate(startDate1,endDate1)
        let startDate = dateData.startDate;
        let endDate= dateData.endDate;
        let month = moment(startDate).format('MM');
        let access_token=await dTalkApiUtil.getAccessToken();
        let authority=await formDataService.getAuthrity(leaderId,access_token)//权限
        let groupName=authority.groupName;
        let dataCache: any = []
        let list:any[]=[]
        let arr=await emplModel.distinct('userId',{})
        if (groupName.includes('销售')||(!groupName.includes('销售')&&comment=='个人'&&character)) {//销售
            if (comment=='个人') {
                let userId:any = ''; 
                let num3 =parseInt( moment(startDate).format('DD'));
                let num4 =parseInt( moment(endDate).format('DD'));
                let dateList=await formDataService.getDate2(num3,num4,startDate)//日期
                if(character==''){
                    userId = leaderId;
                }else{
                   userId=character;
                }
                let name:any='';
                let data5=await visitMonthPlanModel.findOne({userId:userId,'$and':[{user:{$ne:null}},{user:{$ne:''}}]})
                if(data5){
                    name=data5.user
                }else{
                    let employeeInfo:any = ''
                    if(userId==leaderId){
                        employeeInfo=authority.leaderInfo
                    }else{
                        employeeInfo = await dTalkApi.getUserDetail(userId,access_token);
                    }
                    if (employeeInfo&&employeeInfo.name) {
                        name=employeeInfo.name
                    }
                }
                //在这个时间段内,哪些天员工是有计划的
                let dateArr=await visitMonthPlanModel.distinct('planDate',{"$and": [{ planDate: { "$gte": dateData.startDate } }, { planDate: { "$lte": dateData.endDate } }],userId: userId,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] })
                if (dateList.length > 0) {
                    for (let index = 0; index < dateList.length; index++) {
                        let date = dateList[index];
                        let consumerRate_:any=0;
                        if(dateArr.includes(date)){
                            consumerRate_=await formDataService.getConsumerRate_one_employeeDate1ToDate2(userId, date, date);
                        }
                        let consumerRate = (consumerRate_.toFixed(2)-0)*100;
                        dataCache.push({
                            comment: '一天',
                            userId: userId,
                            userName: name,
                            date:date,
                            consumerRate: consumerRate.toFixed(0)
                        })
                    }
                }
            }
        }else{
            let userList: any[] = [];
            if(authority.leaderDepts.length>0){
                let sonData=await formDataService.getsonDept(authority.leaderDepts,true,access_token,arr);
                let patt1 = new RegExp(/\s+/g);  
                let today=moment().format('YYYY-MM-DD');
                if (comment == '个人') {
                    if(!character){
                        if(sonData.userIdData.length>0){
                            for (let index = 0; index < sonData.userIdData.length; index++) {
                                let element2 = sonData.userIdData[index];
                                let emp=await visitMonthPlanModel.findOne({userId:element2,"$and":[{user:{$ne:''}},{user:{$ne:null}}]},{user:1})
                                if (!dataCache[emp.user]) {
                                    dataCache[emp.user] = {
                                        areaName:emp.user,
                                        consumerRate:''
                                    } 
                                }
                                //新的
                                let data_9:any[]=[]
                                if(endDate!=today){
                                    data_9=await excelExportModel.find({userId:element2,"$and":[{date_:{$gte:startDate}},{date_:{$lte:endDate}}]});
                                }else{
                                    data_9=await excelExportModel.find({userId:element2,"$and":[{date_:{$gte:startDate}},{date_:{$lt:endDate}}]});
                                }
                                let numAll_plan=0;
                                let numAll_visit=0;
                                if(data_9.length>0){
                                    data_9.map(it=>{
                                        if(it){
                                            numAll_plan+=it.visitCount_plan;
                                            numAll_visit+=it.actuall_visitCount;
                                        }
                                    })
                                }
                                if(endDate==today){
                                    //今天(当天)计划拜访的客户数量
                                    let count_plan_consumer=await visitMonthPlanModel.count({planDate: endDate, userId: element2,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                                    //console.log('KKKKKKKKKKKKKKKKK',count_plan_consumer)
                                    if(count_plan_consumer==0){
                                        numAll_plan+=0;
                                        numAll_visit+=0;
                                    }else{
                                        //今天(当天)实际已经拜访的客户数量
                                        let count_visited_consumer = await consumerRecoderModel.count({planDate:endDate, userid: element2, comment: 2});
                                        let count_visited_store=await storeRecoderModel.count({ planDate: endDate, userid: element2})
                                        numAll_plan+=count_plan_consumer;
                                        numAll_visit+=(count_visited_consumer+count_visited_store)
                                    }
                                }
                                let consumerRate_one_employee:any=0;
                                if(numAll_plan==0){
                                    consumerRate_one_employee=0;
                                }else{
                                    consumerRate_one_employee=(numAll_visit/numAll_plan);
                                }
                                //旧的
                                //let consumerRate_one_employee = await formDataService.getConsumerRate_one_employeeDate1ToDate2(element2, startDate, endDate);
                                let rate:any=consumerRate_one_employee
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[emp.user]={
                                    areaName:emp.user,
                                    consumerRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                }else if (comment == '城市类型') {
                    let cityTypeList=await consumerRecoderModel.distinct("cityType",{comment:1,"$and":[{cityType:{$ne:''}},{cityType:{$ne:null}}]})
                    if(cityTypeList.length>0){
                        for (let cityindex = 0; cityindex < cityTypeList.length; cityindex++) {
                            let element = cityTypeList[cityindex];
                            if (!dataCache[element]) {
                                dataCache[element] = {
                                    areaName:element,
                                    consumerRate:''
                                }
                            }
                            userList=await consumerRecoderModel.distinct("userid",{cityType:element,comment:1,userid:{$in:sonData.userIdData}})
                            let consumerRate_area=0;//客户拜访成功率
                            let rate:any=0;
                            /* //旧的
                            if(userList.length>0){
                                for (let userindex = 0; userindex < userList.length; userindex++) {
                                    let element2 = userList[userindex];
                                    let consumerRate_one_employee = await formDataService.getConsumerRate_one_employeeDate1ToDate2(element2, startDate, endDate);
                                    consumerRate_area+=consumerRate_one_employee;
                                }
                                rate=(consumerRate_area/userList.length);
                            } */
                           
                            //修改后的
                            //endDate的日期比当天的日期小
                            if(userList.length>0){
                                for (let userindex = 0; userindex < userList.length; userindex++) {
                                    let ele_u = userList[userindex];
                                    let data_9:any[]=[]
                                    if(endDate!=today){
                                        data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:startDate}},{date_:{$lte:endDate}}]});
                                    }else{
                                        data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:startDate}},{date_:{$lt:endDate}}]});
                                    }
                                    let numAll_plan=0;
                                    let numAll_visit=0;
                                    if(data_9.length>0){
                                        data_9.map(it=>{
                                            if(it){
                                                numAll_plan+=it.visitCount_plan;
                                                numAll_visit+=it.actuall_visitCount;
                                            }
                                        })
                                    }
                                    if(endDate==today){
                                        //今天(当天)计划拜访的客户数量
                                        let count_plan_consumer=await visitMonthPlanModel.count({planDate: endDate, userId: ele_u,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                                        //console.log('KKKKKKKKKKKKKKKKK',count_plan_consumer)
                                        if(count_plan_consumer==0){
                                            numAll_plan+=0;
                                            numAll_visit+=0;
                                        }else{
                                            //今天(当天)实际已经拜访的客户数量
                                            let count_visited_consumer = await consumerRecoderModel.count({planDate:endDate, userid: ele_u, comment: 2});
                                            let count_visited_store=await storeRecoderModel.count({ planDate: endDate, userid: ele_u})
                                            numAll_plan+=count_plan_consumer;
                                            numAll_visit+=(count_visited_consumer+count_visited_store)
                                        }
                                    }
                                    if(numAll_plan==0){
                                        consumerRate_area+=0;
                                    }else{
                                        consumerRate_area+=(numAll_visit/numAll_plan);
                                    }
                                }
                                rate=(consumerRate_area/userList.length);
                            }
                            let a=(rate.toFixed(2)-0)*100;
                            dataCache[element]={
                                areaName:element,
                                consumerRate:a.toFixed(0)
                            }
                        }
                    }
                }else if (comment == '客户类型1') {
                    let typeList=await consumerRecoderModel.distinct("typeOne",{comment:1,"$and":[{typeOne:{$ne:null}},{typeOne:{$ne:''}}]})
                    if(typeList.length>0){
                        for (let index1 = 0; index1 < typeList.length; index1++) {
                            let element = typeList[index1];
                            if(element=='0'){
                                continue;
                            }
                            if (patt1.test(element)) {  
                                console.log("有空格");  
                                let d=element.replace(new RegExp(' ',"gm"), '')
                                if(!d){
                                    continue;
                                }
                            } 
                            if (!dataCache[element]) {
                                dataCache[element] = {
                                    areaName:element,
                                    consumerRate:''
                                }
                            }
                            userList = await consumerRecoderModel.distinct("userid", { typeOne: element, comment: 1,userid:{$in:sonData.userIdData}});
                            let rate:any=0;
                            let consumerRate_area=0;//客户拜访成功率
                            //修改后的
                            //endDate的日期比当天的日期小
                            if(userList.length>0){
                                for (let userindex = 0; userindex < userList.length; userindex++) {
                                    let ele_u = userList[userindex];
                                    let data_9:any[]=[]
                                    if(endDate!=today){
                                        data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:startDate}},{date_:{$lte:endDate}}]});
                                    }else{
                                        data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:startDate}},{date_:{$lt:endDate}}]});
                                    }
                                    let numAll_plan=0;
                                    let numAll_visit=0;
                                    if(data_9.length>0){
                                        data_9.map(it=>{
                                            if(it){
                                                numAll_plan+=it.visitCount_plan;
                                                numAll_visit+=it.actuall_visitCount;
                                            }
                                        })
                                    }
                                    if(endDate==today){
                                        //今天(当天)计划拜访的客户数量
                                        let count_plan_consumer=await visitMonthPlanModel.count({planDate: endDate, userId: ele_u,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                                        //console.log('KKKKKKKKKKKKKKKKK',count_plan_consumer)
                                        if(count_plan_consumer==0){
                                            numAll_plan+=0;
                                            numAll_visit+=0;
                                        }else{
                                            //今天(当天)实际已经拜访的客户数量
                                            let count_visited_consumer = await consumerRecoderModel.count({planDate:endDate, userid: ele_u, comment: 2});
                                            let count_visited_store=await storeRecoderModel.count({ planDate: endDate, userid: ele_u})
                                            numAll_plan+=count_plan_consumer;
                                            numAll_visit+=(count_visited_consumer+count_visited_store)
                                        }
                                    }
                                    if(numAll_plan==0){
                                        consumerRate_area+=0;
                                    }else{
                                        consumerRate_area+=(numAll_visit/numAll_plan);
                                    }
                                }
                                rate=(consumerRate_area/userList.length);
                            }
                            let a=(rate.toFixed(2)-0)*100
                            dataCache[element]={
                                areaName:element,
                                consumerRate:a.toFixed(0)
                            }
                        }
                    }
                }else if (comment == '客户类型2') {
                    let typeList=await consumerRecoderModel.distinct("typeTwo",{comment:1,"$and":[{typeTwo:{$ne:''}},{typeTwo:{$ne:null}}]})
                    if(typeList.length>0){ 
                        for (let index1 = 0; index1 < typeList.length; index1++) {
                            let element = typeList[index1];
                            if(element=='0'){
                                continue;
                            }
                            if (patt1.test(element)) {  
                                console.log("有空格");  
                                let d=element.replace(new RegExp(' ',"gm"), '')
                                if(!d){
                                    continue;
                                }
                            } 
                            if (!dataCache[element]) {
                                dataCache[element] = {
                                    areaName:element,
                                    consumerRate:''
                                }
                            }
                            userList = await consumerRecoderModel.distinct("userid", { typeTwo: element, comment: 1,"$and":[{userid:{$in:sonData.userIdData}},{userid:{$ne:''}},{userid:{$ne:null}}]});
                            let consumerRate_area=0;//客户拜访成功率
                            let rate:any=0;
                            //修改后的
                            //endDate的日期比当天的日期小
                            if(userList.length>0){
                                for (let userindex = 0; userindex < userList.length; userindex++) {
                                    let ele_u = userList[userindex];
                                    let data_9:any[]=[]
                                    if(endDate!=today){
                                        data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:startDate}},{date_:{$lte:endDate}}]});
                                    }else{
                                        data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:startDate}},{date_:{$lt:endDate}}]});
                                    }
                                    let numAll_plan=0;
                                    let numAll_visit=0;
                                    if(data_9.length>0){
                                        data_9.map(it=>{
                                            if(it){
                                                numAll_plan+=it.visitCount_plan;
                                                numAll_visit+=it.actuall_visitCount
                                            }
                                        })
                                    }
                                    if(endDate==today){
                                        //今天(当天)计划拜访的客户数量
                                        let count_plan_consumer=await visitMonthPlanModel.count({planDate: endDate, userId: ele_u,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                                        //console.log('KKKKKKKKKKKKKKKKK',count_plan_consumer)
                                        if(count_plan_consumer==0){
                                            numAll_plan+=0;
                                            numAll_visit+=0;
                                        }else{
                                            //今天(当天)实际已经拜访的客户数量
                                            let count_visited_consumer = await consumerRecoderModel.count({planDate:endDate, userid: ele_u, comment: 2});
                                            let count_visited_store=await storeRecoderModel.count({ planDate: endDate, userid: ele_u})
                                            numAll_plan+=count_plan_consumer;
                                            numAll_visit+=(count_visited_consumer+count_visited_store)
                                        }
                                    }
                                    //console.log(numAll_visit,'?????????????',numAll_plan,'>>>>>',ele_u)
                                    if(numAll_plan==0){
                                        consumerRate_area+=0;
                                    }else{
                                        consumerRate_area+=(numAll_visit/numAll_plan);
                                    }
                                }
                                rate=(consumerRate_area/userList.length);
                            }
                            let a=(rate.toFixed(2)-0)*100
                            dataCache[element]={
                                areaName:element,
                                consumerRate:a.toFixed(0)
                            }
                        }
                    }
                }else if (comment == '客户类型3') {
                    let typeList=await consumerRecoderModel.distinct("typeThree",{comment:1,"$and":[{typeThree:{$ne:''}},{typeThree:{$ne:null}}]})
                    if(typeList.length>0){
                        for (let index1 = 0; index1 < typeList.length; index1++) {
                            let element = typeList[index1];
                            if(element=='0'){
                                continue;
                            }
                            if (patt1.test(element)) {  
                                console.log("有空格");  
                                let d=element.replace(new RegExp(' ',"gm"), '')
                                if(!d){
                                    continue;
                                }
                            } 
                            if (!dataCache[element]) {
                                dataCache[element] = {
                                    areaName:element,
                                    consumerRate:''
                                }
                            }
                            userList = await consumerRecoderModel.distinct("userid", { typeThree: element, comment: 1,"$and":[{userid:{$in:sonData.userIdData}},{userid:{$ne:''}},{userid:{$ne:null}}]});
                            let consumerRate_area=0;//客户拜访成功率
                            let rate:any=0;
                            //新的
                            if(userList.length>0){
                                for (let userindex = 0; userindex < userList.length; userindex++) {
                                    let ele_u = userList[userindex];
                                    let data_9:any[]=[]
                                    if(endDate!=today){
                                        data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:startDate}},{date_:{$lte:endDate}}]});
                                    }else{
                                        data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:startDate}},{date_:{$lt:endDate}}]});
                                    }
                                    let numAll_plan=0;
                                    let numAll_visit=0;
                                    if(data_9.length>0){
                                        data_9.map(it=>{
                                            if(it){
                                                numAll_plan+=it.visitCount_plan;
                                                numAll_visit+=it.actuall_visitCount;
                                            }
                                        })
                                    }
                                    if(endDate==today){
                                        //今天(当天)计划拜访的客户数量
                                        let count_plan_consumer=await visitMonthPlanModel.count({planDate: endDate, userId: ele_u,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                                        //console.log('KKKKKKKKKKKKKKKKK',count_plan_consumer)
                                        if(count_plan_consumer==0){
                                            numAll_plan+=0;
                                            numAll_visit+=0;
                                        }else{
                                            //今天(当天)实际已经拜访的客户数量
                                            let count_visited_consumer = await consumerRecoderModel.count({planDate:endDate, userid: ele_u, comment: 2});
                                            let count_visited_store=await storeRecoderModel.count({ planDate: endDate, userid: ele_u})
                                            numAll_plan+=count_plan_consumer;
                                            numAll_visit+=(count_visited_consumer+count_visited_store)
                                        }
                                    }
                                    if(numAll_plan==0){
                                        consumerRate_area+=0;
                                    }else{
                                        consumerRate_area+=(numAll_visit/numAll_plan);
                                    }
                                }
                                rate=(consumerRate_area/userList.length);
                            }
                            let a=(rate.toFixed(2)-0)*100
                            dataCache[element]={
                                areaName:element,
                                consumerRate:a.toFixed(0)
                            }
                        }
                    }
                }else{ 
                    let sonData2:any={}
                    if(groupName.includes('区域')||groupName.includes('模块')){
                        sonData2=await formDataService.getsonDept(authority.leaderDepts,false,access_token,arr)
                    }
                    let manage_data:any={}
                    if(groupName.includes('全国')){
                        manage_data=await addNewService.get_model_area_pro_list(access_token);
                    }
                    let son_area_list:any[]=[]//区域部门名称列表
                    let son_province_list:any[]=[]//省份部门名称列表
                    if(groupName.includes('模块')){
                        if(sonData2.listNames.length==0){
                            son_area_list=[];
                            son_province_list=[];
                        }else if(sonData.listNames.length==sonData2.listNames.length&&sonData2.listNames.length>0){
                            son_province_list=[];
                            son_area_list=sonData2.listNames;
                        }else if(sonData.listNames.length !=sonData2.listNames.length&&sonData2.listNames.length>0){
                            son_area_list=sonData2.listNames;
                            sonData.listNames.map(it=>{
                                if(it){
                                    if(!sonData2.listNames.includes(it)){//判断是否是区域部门
                                        if(!son_province_list.includes(it)){//去重
                                            son_province_list.push(it)
                                        }
                                        
                                    }
                                }
                            })
                            /* 
                            for (let index2 = 0; index2 <sonData.listNames.length; index2++) {
                                let element = sonData.listNames[index2];
                                if(sonData2.listNames.includes(element)){
                                    son_province_list.push('')
                                }else{
                                    son_province_list.push(element)
                                }
                            } */
                        }
                    }
                    if(comment=='省份'){
                        let nameList:any[]=[]
                        if(groupName.includes('区域')){//区域负责人
                            nameList=await formDataService.newArray(sonData2.listNames)
                        }else if(groupName.includes('模块')){ //模块负责人
                            if(son_province_list.length>0){
                                son_province_list.map(it=>{
                                    if(it){
                                        nameList.push(it)
                                    }  
                                })
                            }
                        }else if(groupName.includes('全国')){//全国负责人
                            nameList=manage_data.proNames
                        }
                        if(nameList.length>0){
                            for (let sonDeptindex = 0; sonDeptindex < nameList.length; sonDeptindex++) {
                                let pro = nameList[sonDeptindex];
                                if (!dataCache[pro]) {
                                    dataCache[pro] = {
                                        areaName:pro,
                                        consumerRate:''
                                    }
                                }
                                userList = await visitMonthPlanModel.distinct("userId", { provinceName:pro, comment: 1, deptId: { $in:sonData.list }, userId: { $ne: '' } }); 
                                let consumerRate_area=0;//一个区域的客户拜访成功率
                                let rate:any=0;
                                /* //旧的
                                if(userList.length>0){
                                    for (let userindex = 0; userindex < userList.length; userindex++) {
                                        let element2 = userList[userindex];
                                        let consumerRate_one_employee = await formDataService.getConsumerRate_one_employeeDate1ToDate2(element2, startDate, endDate);
                                        consumerRate_area+=consumerRate_one_employee;
                                    }
                                    rate=(consumerRate_area/userList.length);
                                } */
                                //修改后的
                                //endDate的日期比当天的日期小
                                if(userList.length>0){
                                    for (let userindex = 0; userindex < userList.length; userindex++) {
                                        let ele_u = userList[userindex];
                                        let data_9:any[]=[]
                                        if(endDate!=today){
                                            data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:startDate}},{date_:{$lte:endDate}}]});
                                        }else{
                                            data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:startDate}},{date_:{$lt:endDate}}]});
                                        }
                                        let numAll_plan=0;
                                        let numAll_visit=0;
                                        if(data_9.length>0){
                                            data_9.map(it=>{
                                                if(it){
                                                    numAll_plan+=it.visitCount_plan;
                                                    numAll_visit+=it.actuall_visitCount;
                                                }
                                            })
                                        }
                                        if(endDate==today){
                                            //今天(当天)计划拜访的客户数量
                                            let count_plan_consumer=await visitMonthPlanModel.count({planDate: endDate, userId: ele_u,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                                            //console.log('KKKKKKKKKKKKKKKKK',count_plan_consumer)
                                            if(count_plan_consumer==0){
                                                numAll_plan+=0;
                                                numAll_visit+=0;
                                            }else{
                                                //今天(当天)实际已经拜访的客户数量
                                                let count_visited_consumer = await consumerRecoderModel.count({planDate:endDate, userid: ele_u, comment: 2});
                                                let count_visited_store=await storeRecoderModel.count({ planDate: endDate, userid: ele_u})
                                                numAll_plan+=count_plan_consumer;
                                                numAll_visit+=(count_visited_consumer+count_visited_store)
                                            }
                                        }
                                        if(numAll_plan==0){
                                            consumerRate_area+=0;
                                        }else{
                                            consumerRate_area+=(numAll_visit/numAll_plan);
                                        }
                                    }
                                    rate=(consumerRate_area/userList.length);
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[pro]={
                                    areaName:pro,
                                    consumerRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                    if(comment=='区域'){
                        let areaNameList:any[]=[]
                        if(groupName.includes('模块')){
                            areaNameList= son_area_list
                        }else if(groupName.includes('全国')){
                            areaNameList=manage_data.areaNames
                            //areaNameList=await visitMonthPlanModel.distinct("areaName",{comment:1,"$and":[{areaName:{$ne:null}},{areaName:{$ne:''}}]})
                        }
                        if(areaNameList.length>0){
                            for (let index = 0; index < areaNameList.length; index++) {
                                const element = areaNameList[index];
                                if (!dataCache[element]) {
                                    dataCache[element] = {
                                        areaName:element,
                                        consumerRate:''
                                    }
                                }
                                userList = await visitMonthPlanModel.distinct("userId", {areaName:element, deptId: { $in: sonData.list },"$and":[{userId: { $ne: '' }},{userId: { $ne:null}}] });
                                let consumerRate_area=0;//一个区域的客户拜访成功率
                                let rate:any=0;
                                /* //旧的
                                let arr2:any=[]
                                for (let userindex = 0; userindex < userList.length; userindex++) {
                                    let element2 = userList[userindex];
                                    let consumerRate_one_employee = await formDataService.getConsumerRate_one_employeeDate1ToDate2_2(element2, startDate, endDate);
                                    consumerRate_area+=consumerRate_one_employee.rate;
                                    arr2.push({
                                        id:element2,
                                        rate:consumerRate_one_employee.rate,
                                        visit:consumerRate_one_employee.visit,
                                        plan:consumerRate_one_employee.plan
                                    })
                                } */
                                //修改后的
                                //endDate的日期比当天的日期小
                                if(userList.length>0){
                                    for (let userindex = 0; userindex < userList.length; userindex++) {
                                        let ele_u = userList[userindex];
                                        let data_9:any[]=[]
                                        if(endDate!=today){
                                            data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:startDate}},{date_:{$lte:endDate}}]});
                                        }else{
                                            data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:startDate}},{date_:{$lt:endDate}}]});
                                        }
                                        let numAll_plan=0;
                                        let numAll_visit=0;
                                        if(data_9.length>0){
                                            data_9.map(it=>{
                                                if(it){
                                                    numAll_plan+=it.visitCount_plan;
                                                    numAll_visit+=it.actuall_visitCount;
                                                }
                                            })
                                        }
                                        if(endDate==today){
                                            //今天(当天)计划拜访的客户数量
                                            let count_plan_consumer=await visitMonthPlanModel.count({planDate: endDate, userId: ele_u,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                                            //console.log('KKKKKKKKKKKKKKKKK',count_plan_consumer)
                                            if(count_plan_consumer==0){
                                                numAll_plan+=0;
                                                numAll_visit+=0;
                                            }else{
                                                //今天(当天)实际已经拜访的客户数量
                                                let count_visited_consumer = await consumerRecoderModel.count({planDate:endDate, userid: ele_u, comment: 2});
                                                let count_visited_store=await storeRecoderModel.count({ planDate: endDate, userid: ele_u})
                                                numAll_plan+=count_plan_consumer;
                                                numAll_visit+=(count_visited_consumer+count_visited_store)
                                            }
                                        }
                                        if(numAll_plan==0){
                                            consumerRate_area+=0;
                                        }else{
                                            consumerRate_area+=(numAll_visit/numAll_plan);
                                        }
                                    }
                                    rate=(consumerRate_area/userList.length);
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[element]={
                                    areaName:element,
                                    consumerRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                }
            }
        } 
        for (const key in dataCache) { //移植dataCache当中的属性到list当中
            if (dataCache.hasOwnProperty(key)) {
                const element = dataCache[key];
                list.push(element)
            }
        }
        if(list.length==0){
            list.push({
                areaName:'',
                consumerRate:0
            })
        }
        console.log(list,'list_list_list_list_list_list_list_list_客户拜访达成率',list.length)
        return list;
    }

    //(二)新客户拜访达成率----报表
    async getReach_NewConsumerRate(startDate1: string, endDate1: string, character: string, comment: string, leaderId: string) {
        let list: any[] = [];
        let dateData=await formDataService.getDate(startDate1,endDate1)
        let date1 = dateData.startDate;
        let date2= dateData.endDate;
        let access_token=await dTalkApiUtil.getAccessToken();
        let authority=await formDataService.getAuthrity(leaderId,access_token)  //权限问题
        let groupName=authority.groupName;
        let dataCache: any = []
        let arr=await emplModel.distinct('userId',{})
        if (groupName.includes('销售')||(!groupName.includes('销售')&&comment=='个人'&&character)) {//销售
            if (comment=='个人') {
                let userId:any = '';
                let num3 =parseInt( moment(date1).format('DD'));
                let num4 =parseInt( moment(date2).format('DD'));
                let dateList=await formDataService.getDate2(num3,num4,date1)//日期
                if(character==''){
                    userId = leaderId;
                }else{
                   userId=character;
                }
                let name:any='';
                let data5=await visitMonthPlanModel.findOne({userId:userId,'$and':[{user:{$ne:null}},{user:{$ne:''}}]})
                if(data5){
                    name=data5.user
                }else{
                    let employeeInfo:any = ''
                    if(userId==leaderId){
                        employeeInfo=authority.leaderInfo
                    }else{
                        employeeInfo = await dTalkApi.getUserDetail(userId,access_token);
                    }
                    if (employeeInfo&&employeeInfo.name) {
                        name=employeeInfo.name
                    }
                }
                //在这个时间段内,哪些天员工是有计划的
                let dateArr=await visitMonthPlanModel.distinct('planDate',{"$and": [{ planDate: { "$gte": dateData.startDate } }, { planDate: { "$lte": dateData.endDate } }],userId: userId,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] })
                if (dateList.length > 0) {
                    for (let index = 0; index < dateList.length; index++) {
                        let date = dateList[index];
                        let consumerRate_:any=0;
                        if(dateArr.includes(date)){
                            consumerRate_=await formDataService.getConsumerRate_one_employeeDate1ToDate2(userId, date, date);
                        }
                        let consumerRate = (consumerRate_.toFixed(2)-0)*100;
                        dataCache.push({
                            comment: '一天',
                            userId: userId,
                            userName: name,
                            date:date,
                            consumerRate: consumerRate.toFixed(0)
                        })
                    }
                }
            }
        }else{
            let userList: any[] = [];
            if(authority.leaderDepts.length>0){
                let sonData=await formDataService.getsonDept(authority.leaderDepts,true,access_token,arr);
                let userList2=sonData.userIdData;
                let patt1 = new RegExp(/\s+/g);  
                let today=moment().format('YYYY-MM-DD');
                if (comment == '个人') {
                    if(!character){
                        if(userList2.length>0){
                            for (let index = 0; index < userList2.length; index++) {
                                let element2 = userList2[index];
                                let emp=await visitMonthPlanModel.findOne({userId:element2,"$and":[{user:{$ne:''}},{user:{$ne:null}}]})
                                if (!dataCache[emp.user]) {
                                    dataCache[emp.user] = {
                                        areaName:emp.user,
                                        newconsumerRate:''
                                    }
                                }
                                let consumerRate_one_employee:any=0;
                                //新的
                                if(date2!=today){
                                    let data_9=await excelExportModel.find({userId:element2,"$and":[{date_:{$gte:date1}},{date_:{$lte:date2}}]});
                                    let numAll_plan=0;
                                    let numAll_visit=0;
                                    if(data_9.length>0){
                                        data_9.map(it=>{
                                            if(it){
                                                numAll_plan+=it.newConsumerCount_plan;
                                                numAll_visit+=it.newConsumerCount_visit;
                                            }
                                        })
                                    }
                                    if(numAll_plan==0){
                                        consumerRate_one_employee=0;
                                    }else{
                                        consumerRate_one_employee=(numAll_visit/numAll_plan);
                                    }
                                }else{
                                    //旧的
                                    consumerRate_one_employee = await formDataService.getRate_NewConsumer_one_employeeDate1ToDate2(element2, date1, date2);
                                }
                                let a=(consumerRate_one_employee.toFixed(2)-0)*100
                                dataCache[emp.user]={
                                    areaName:emp.user,
                                    newconsumerRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                }else if (comment == '城市类型') {
                    let cityTypeList=await consumerRecoderModel.distinct("cityType",{comment:1,"$and":[{cityType:{$ne:null}},{cityType:{$ne:''}}]})
                    if(cityTypeList.length>0){
                        for (let cityindex = 0; cityindex < cityTypeList.length; cityindex++) {
                            let element = cityTypeList[cityindex];
                            if (!dataCache[element]) {
                                dataCache[element] = {
                                    areaName:element,
                                    newconsumerRate:''
                                }
                            }
                            userList=await consumerRecoderModel.distinct("userid",{cityType:element,comment:1,userid:{$in:userList2}})
                            let consumerRate_area=0;//客户拜访成功率
                            let rate:any=0;
                            if(userList.length>0){
                                for (let userindex = 0; userindex < userList.length; userindex++) {
                                    let element2 = userList[userindex];
                                    let consumerRate_one_employee = await formDataService.getRate_NewConsumer_one_employeeDate1ToDate2(element2, date1, date2);
                                    consumerRate_area+=consumerRate_one_employee;
                                }
                                rate=(consumerRate_area/userList.length);
                            }
                            let a=(rate.toFixed(2)-0)*100
                            dataCache[element]={
                                areaName:element,
                                newconsumerRate:a.toFixed(0)
                            }
                        }
                    }
                }else if (comment == '客户类型1') {
                    let typeList=await consumerRecoderModel.distinct("typeOne",{comment:1,"$and":[{typeOne:{$ne:null}},{typeOne:{$ne:''}}]})
                    if(typeList.length>0){
                        for (let index1 = 0; index1 < typeList.length; index1++) {
                            let element = typeList[index1];
                            if (patt1.test(element)) {  
                                console.log("有空格");  
                                let d=element.replace(new RegExp(' ',"gm"), '')
                                if(!d){
                                    continue;
                                }
                            } 
                            if(element!='0'){
                                if (!dataCache[element]) {
                                    dataCache[element] = {
                                        areaName:element,
                                        newconsumerRate:''
                                    }
                                }
                                userList = await consumerRecoderModel.distinct("userid", { typeOne: element, comment: 1,"$and":[{userid:{$in:userList2}},{userid:{$ne:null}}]});
                                let consumerRate_area=0;//客户拜访成功率
                                let rate:any=0;
                                if(date2!=today){
                                     //修改后的
                                    //endDate的日期比当天的日期小
                                    if(userList.length>0){
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let ele_u = userList[userindex];
                                            let data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:date1}},{date_:{$lte:date2}}]});
                                            let numAll_plan=0;
                                            let numAll_visit=0;
                                            if(data_9.length>0){
                                                data_9.map(it=>{
                                                    if(it){
                                                        numAll_plan+=it.newConsumerCount_plan;
                                                        numAll_visit+=it.newConsumerCount_visit;
                                                    }
                                                })
                                            }
                                            if(numAll_plan==0){
                                                consumerRate_area+=0;
                                            }else{
                                                consumerRate_area+=(numAll_visit/numAll_plan);
                                            }
                                        }
                                        rate=(consumerRate_area/userList.length);
                                    }
                                }else{
                                    if(userList.length>0){
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let element2 = userList[userindex];
                                            let consumerRate_one_employee = await formDataService.getRate_NewConsumer_one_employeeDate1ToDate2(element2, date1, date2);
                                            consumerRate_area+=consumerRate_one_employee;
                                        }
                                        rate=(consumerRate_area/userList.length);
                                    }
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[element]={
                                    areaName:element,
                                    newconsumerRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                }else if (comment == '客户类型2') {
                    let typeList=await consumerRecoderModel.distinct("typeTwo",{comment:1,"$and":[{typeTwo:{$ne:null}},{typeTwo:{$ne:''}}]})
                    if(typeList.length>0){
                        for (let index1 = 0; index1 < typeList.length; index1++) {
                            let element = typeList[index1];
                            if (patt1.test(element)) {  
                                console.log("有空格");  
                                let d=element.replace(new RegExp(' ',"gm"), '')
                                if(!d){
                                    continue;
                                }
                            } 
                            if(element!='0'){
                                if (!dataCache[element]) {
                                    dataCache[element] = {
                                        areaName:element,
                                        newconsumerRate:''
                                    }
                                }
                                userList = await consumerRecoderModel.distinct("userid", { typeTwo: element, comment: 1,"$and":[{userid:{$in:userList2}},{userid:{$ne:null}}]});
                                let newconsumerRate_area=0;//客户拜访成功率
                                let rate:any=0;
                                if(date2!=today){
                                    if(userList.length>0){
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let ele_u = userList[userindex];
                                            let data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:date1}},{date_:{$lte:date2}}]});
                                            let numAll_plan=0;
                                            let numAll_visit=0;
                                            if(data_9.length>0){
                                                data_9.map(it=>{
                                                    if(it){
                                                        numAll_plan+=it.newConsumerCount_plan;
                                                        numAll_visit+=it.newConsumerCount_visit;
                                                    }
                                                })
                                            }
                                            if(numAll_plan==0){
                                                newconsumerRate_area+=0;
                                            }else{
                                                newconsumerRate_area+=(numAll_visit/numAll_plan);
                                            }
                                        }
                                        rate=(newconsumerRate_area/userList.length);
                                    }
                                }else{
                                    if(userList.length>0){
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let element2 = userList[userindex];
                                            let consumerRate_one_employee = await formDataService.getRate_NewConsumer_one_employeeDate1ToDate2(element2, date1, date2);
                                            newconsumerRate_area+=consumerRate_one_employee;
                                        }
                                        rate=(newconsumerRate_area/userList.length);
                                    }
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[element]={
                                    areaName:element,
                                    newconsumerRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                }else if (comment == '客户类型3') {
                    let typeList=await consumerRecoderModel.distinct("typeThree",{comment:1,"$and":[{typeThree:{$ne:null}},{typeThree:{$ne:''}}]})
                    if(typeList.length>0){
                        for (let index1 = 0; index1 < typeList.length; index1++) {
                            let element = typeList[index1];
                            if (patt1.test(element)) {  
                                console.log("有空格");  
                                let d=element.replace(new RegExp(' ',"gm"), '')
                                if(!d){
                                    continue;
                                }
                            } 
                            if(element!='0'){
                                if (!dataCache[element]) {
                                    dataCache[element] = {
                                        areaName:element,
                                        newconsumerRate:''
                                    }
                                }
                                userList = await consumerRecoderModel.distinct("userid", { typeThree: element, comment: 1,"$and":[{userid:{$in:userList2}},{userid:{$ne:null}}]});
                                let consumerRate_area=0;//客户拜访成功率
                                let rate:any=0;
                                if(date2!=today){
                                    if(userList.length>0){
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let ele_u = userList[userindex];
                                            let data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:date1}},{date_:{$lte:date2}}]});
                                            let numAll_plan=0;
                                            let numAll_visit=0;
                                            if(data_9.length>0){
                                                data_9.map(it=>{
                                                    if(it){
                                                        numAll_plan+=it.newConsumerCount_plan;
                                                        numAll_visit+=it.newConsumerCount_visit;
                                                    }
                                                })
                                            }
                                            if(numAll_plan==0){
                                                consumerRate_area+=0;
                                            }else{
                                                consumerRate_area+=(numAll_visit/numAll_plan);
                                            }
                                        }
                                        rate=(consumerRate_area/userList.length);
                                    }
                                }else{
                                    if(userList.length>0){
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let element2 = userList[userindex];
                                            let consumerRate_one_employee = await formDataService.getRate_NewConsumer_one_employeeDate1ToDate2(element2, date1, date2);
                                            consumerRate_area+=consumerRate_one_employee;
                                        }
                                        rate=(consumerRate_area/userList.length);
                                    }
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[element]={
                                    areaName:element,
                                    newconsumerRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                }else{
                    let sonData2:any={}
                    if(groupName.includes('区域')||groupName.includes('模块')){
                        sonData2=await formDataService.getsonDept(authority.leaderDepts,false,access_token,arr)
                    }
                    let manage_data:any={}
                    if(groupName.includes('全国')){
                        manage_data=await addNewService.get_model_area_pro_list(access_token);
                    }
                    let son_area_list:any[]=[]//区域部门名称列表
                    let son_province_list:any[]=[]//省份部门名称列表
                    if(groupName.includes('模块')){
                        if(sonData2.listNames.length==0){
                            son_area_list=[];
                            son_province_list=[];
                        }else if(sonData.listNames.length==sonData2.listNames.length&&sonData2.listNames.length>0){
                            son_province_list=[];
                            son_area_list=sonData2.listNames;
                        }else if(sonData.listNames.length !=sonData2.listNames.length&&sonData2.listNames.length>0){
                            son_area_list=sonData2.listNames;
                            sonData.listNames.map(it=>{
                                if(it){
                                    if(!sonData2.listNames.includes(it)){//判断是否是区域部门
                                        if(!son_province_list.includes(it)){//去重
                                            son_province_list.push(it)
                                        }
                                        
                                    }
                                }
                            })
                        }
                    }
                    if(comment=='省份'){
                        let nameList:any[]=[]
                        if(groupName.includes('区域')){//区域负责人
                            nameList=await formDataService.newArray(sonData2.listNames)
                        }else if(groupName.includes('模块')){ //模块负责人
                            if(son_province_list.length>0){
                                son_province_list.map(it=>{
                                    if(it){
                                        nameList.push(it)
                                    }  
                                })
                            }
                        }else if(groupName.includes('全国')){//全国负责人
                            nameList=manage_data.proNames
                        }
                        if(nameList.length>0){
                            for (let sonDeptindex = 0; sonDeptindex < nameList.length; sonDeptindex++) {
                                let pro = nameList[sonDeptindex];
                                if (!dataCache[pro]) {
                                    dataCache[pro] = {
                                        areaName:pro,
                                        consumerRate:''
                                    }
                                }
                                userList = await visitMonthPlanModel.distinct("userId", { provinceName:pro, comment: 1, deptId: { $in:sonData.list }, userId: { $ne: '' } }); 
                                let consumerRate_area=0;//一个省份的新客户拜访成功率
                                let rate:any=0;
                                //修改后的
                                if(userList.length>0){
                                    if(date2!=today){
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let ele_u = userList[userindex];
                                            let data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:date1}},{date_:{$lte:date2}}]});
                                            let numAll_plan=0;
                                            let numAll_visit=0;
                                            if(data_9.length>0){
                                                data_9.map(it=>{
                                                    if(it){
                                                        numAll_plan+=it.newConsumerCount_plan;
                                                        numAll_visit+=it.newConsumerCount_visit;
                                                    }
                                                })
                                            }
                                            if(numAll_plan==0){
                                                consumerRate_area+=0;
                                            }else{
                                                consumerRate_area+=(numAll_visit/numAll_plan);
                                            }
                                        }
                                    }else{
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let element2 = userList[userindex];
                                            let consumerRate_one_employee = await formDataService.getRate_NewConsumer_one_employeeDate1ToDate2(element2, date1, date2);
                                            consumerRate_area+=consumerRate_one_employee;
                                        }
                                    }
                                    rate=(consumerRate_area/userList.length);
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[pro]={
                                    areaName:pro,
                                    consumerRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                    if(comment=='区域'){
                        let areaNameList:any[]=[]
                        if(groupName.includes('模块')){
                            areaNameList= son_area_list
                        }else if(groupName.includes('全国')){
                            areaNameList=manage_data.areaNames
                        }
                        if(areaNameList.length>0){
                            for (let index = 0; index < areaNameList.length; index++) {
                                const element = areaNameList[index];
                                if (!dataCache[element]) {
                                    dataCache[element] = {
                                        areaName:element,
                                        consumerRate:''
                                    }
                                }
                                userList = await visitMonthPlanModel.distinct("userId", {areaName:element, deptId: { $in: sonData.list },"$and":[{userId: { $ne: '' }},{userId: { $ne:null}}] });
                                let consumerRate_area=0;//一个区域的新客户拜访成功率
                                let rate:any=0;
                                //新的
                                if(userList.length>0){
                                    if(date2!=today){
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let ele_u = userList[userindex];
                                            let data_9=await excelExportModel.find({userId:ele_u,"$and":[{date_:{$gte:date1}},{date_:{$lte:date2}}]});
                                            let numAll_plan=0;
                                            let numAll_visit=0;
                                            if(data_9.length>0){
                                                data_9.map(it=>{
                                                    if(it){
                                                        numAll_plan+=it.newConsumerCount_plan;
                                                        numAll_visit+=it.newConsumerCount_visit;
                                                    }
                                                })
                                            }
                                            if(numAll_plan==0){
                                                consumerRate_area+=0;
                                            }else{
                                                consumerRate_area+=(numAll_visit/numAll_plan);
                                            }
                                        }
                                    }else{
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let element2 = userList[userindex];
                                            let consumerRate_one_employee = await formDataService.getRate_NewConsumer_one_employeeDate1ToDate2(element2, date1, date2);
                                            consumerRate_area+=consumerRate_one_employee;
                                        }
                                    }
                                    rate=(consumerRate_area/userList.length);
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[element]={
                                    areaName:element,
                                    consumerRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                }
            }
        }
        for (const key in dataCache) { //移植dataCache当中的属性到list当中
            if (dataCache.hasOwnProperty(key)) {
                const element = dataCache[key];
                list.push(element)
            }
        }
        if(list.length==0){
            list.push({
                areaName:'',
                newconsumerRate:0
            })
        }
        console.log(list,'list_list_list_list_list_list_list_list_新客户拜访达成率',list.length)
        return list;
    }

    //(三)已拜访门店拜访达标率------报表
    async getReach_VisitedStoreRate(startDate1: string, endDate1: string, character: string, comment: string, leaderId: string) {
        let dateData=await formDataService.getDate(startDate1,endDate1)
        let date1 = dateData.startDate;
        let date2= dateData.endDate;
        let access_token=await dTalkApiUtil.getAccessToken();
        let authority=await formDataService.getAuthrity(leaderId,access_token) //权限问题
        let groupName=authority.groupName;
        let dataCache: any = []
        let list: any[] = [];
        let arr=await emplModel.distinct('userId',{})
        if (groupName.includes('销售')||(!groupName.includes('销售')&&comment=='个人'&&character)) {//销售
            if (comment=='个人') {
                let userId:any = '';
                let num3 =parseInt( moment(date1).format('DD'));
                let num4 =parseInt( moment(date2).format('DD'));
                let dateList=await formDataService.getDate2(num3,num4,date1)//日期
                if(character==''){
                    userId = leaderId;
                }else{
                   userId=character;
                }
                let name:any='';
                let data5=await visitMonthPlanModel.findOne({userId:userId,'$and':[{user:{$ne:null}},{user:{$ne:''}}]})
                if(data5){
                    name=data5.user
                }else{
                    let employeeInfo:any = ''
                    if(userId==leaderId){
                        employeeInfo=authority.leaderInfo
                    }else{
                        employeeInfo = await dTalkApi.getUserDetail(userId,access_token);
                    }
                    if (employeeInfo&&employeeInfo.name) {
                        name=employeeInfo.name
                    }
                }
                //在这个时间段内,哪些天员工是有门店拜访记录
                let dateArr=await storeRecoderModel.distinct('planDate',{"$and": [{ planDate: { "$gte": dateData.startDate } }, { planDate: { "$lte": dateData.endDate } }],userId: userId,planType: '门店'})
                if (dateList.length > 0) {
                    for (let index = 0; index < dateList.length; index++) {
                        let date = dateList[index];
                        let consumerRate_:any=0;
                        if(dateArr.includes(date)){
                            consumerRate_= await formDataService.getReachStoreRate_one_employeeDate1ToDate2(userId, date, date);
                        }
                        let consumerRate = (consumerRate_.toFixed(2)-0)*100;
                        dataCache.push({
                            comment: '一天',
                            userId: userId,
                            userName: name,
                            date:date,
                            consumerRate: consumerRate.toFixed(0)
                        })
                    }
                }
            }
        }else{
            let userList: any[] = [];
            if( authority.leaderDepts.length>0){
                let sonDept:any=[]
                let sonData=await formDataService.getsonDept( authority.leaderDepts,true,access_token,arr);
                let userList2=sonData.userIdData;
                let today=moment().format('YYYY-MM-DD');
                if (comment == '个人') {
                    if(!character){
                        if(userList2.length>0){
                            for (let index = 0; index < userList2.length; index++) {
                                let element2 = userList2[index];
                                let emp=await visitMonthPlanModel.findOne({userId:element2,"$and":[{user:{$ne:''}},{user:{$ne:null}}]})
                                if (!dataCache[emp.user]) {
                                    dataCache[emp.user] = {
                                        areaName:emp.user,
                                        reachStoreRate:''
                                    }
                                }
                                let storeRate_one_employee:any=0;
                                if(date2!=today){
                                    let data_9=await excelExportModel.find({userId:element2,"$and":[{date_:{$gte:date1}},{date_:{$lte:date2}}]});
                                    let numAll_store_reach=0;//已经拜访的门店中门店达标的数量
                                    let numAll_visit=0;//已经拜访的门店数量
                                    if(data_9.length>0){
                                        data_9.map(it=>{
                                            if(it){
                                                numAll_store_reach+=it.reachStandardStoreCount;
                                                numAll_visit+=it.visitedStoreCount;
                                            }
                                        })
                                    }
                                    if(numAll_visit==0){
                                        storeRate_one_employee=0;
                                    }else{
                                        storeRate_one_employee=(numAll_store_reach/numAll_visit);
                                    }
                                }else{
                                    storeRate_one_employee = await formDataService.getReachStoreRate_one_employeeDate1ToDate2(element2, date1, date2);
                                }
                                let a=(storeRate_one_employee.toFixed(2)-0)*100
                                dataCache[emp.user]={
                                    areaName:emp.user,
                                    reachStoreRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                }else if (comment == '店铺等级') {
                    let storeTypeList2=await storeInfoModel.distinct("store_classification",{"$and":[{store_classification:{$ne:null}},{store_classification:{$ne:''}}]});
                    //去除数组元素的首尾空格并去重
                    let storeTypeList:any=[]
                    if(storeTypeList2.length>0){
                        storeTypeList2.map(it=>{
                            if(it){
                                let a=it.trim();
                                if(!storeTypeList.includes(a)){
                                    storeTypeList.push(a)
                                }
                            }
                        })
                    }
                    if(storeTypeList.length>0){
                        for (let index = 0; index < storeTypeList.length; index++) {
                            let element = storeTypeList[index];
                            if (!dataCache[element]) {
                                dataCache[element] = {
                                    areaName:element,
                                    reachStoreRate:''
                                }
                            }
                            let consumerCodeList = await storeInfoModel.distinct("consumerCode", { store_classification: element,"$and":[{consumerCode:{$ne:null}},{consumerCode:{$ne:''}}]});
                            userList = await consumerRecoderModel.distinct("userid", { consumerCode: { $in: consumerCodeList }, comment: 1, "$and":[{userid:{$in:userList2}},{userid:{$ne:null}},{userid:{$ne:''}}] })
                            let storeRate_area=0;//已拜访门店拜访达标率
                            let rate:any=0;
                            if(userList.length>0){
                                for (let userindex = 0; userindex < userList.length; userindex++) {
                                    let element2 = userList[userindex];
                                    let  reachStoreRate_one_employee = await formDataService.getReachStoreRate_one_employeeDate1ToDate2(element2, date1, date2);
                                    storeRate_area+=reachStoreRate_one_employee;
                                }
                                rate=(storeRate_area/userList.length);
                            }
                            let a=(rate.toFixed(2)-0)*100
                            dataCache[element]={
                                areaName:element,
                                reachStoreRate: a.toFixed(0)
                            }
                        }
                    }
                }else{
                    let sonData2:any={}
                    if(groupName.includes('区域')||groupName.includes('模块')){
                        sonData2=await formDataService.getsonDept( authority.leaderDepts,false,access_token,arr)
                    }
                    let manage_data:any={}
                    if(groupName.includes('全国')){
                        manage_data=await addNewService.get_model_area_pro_list(access_token);
                    }
                    let son_area_list:any[]=[]//区域部门名称列表
                    let son_province_list:any[]=[]//省份部门名称列表
                    if(groupName.includes('模块')){
                        if(sonData2.listNames.length==0){
                            son_area_list=[];
                            son_province_list=[];
                        }else if(sonData.listNames.length==sonData2.listNames.length&&sonData2.listNames.length>0){
                            son_province_list=[];
                            son_area_list=sonData2.listNames;
                        }else if(sonData.listNames.length !=sonData2.listNames.length&&sonData2.listNames.length>0){
                            son_area_list=sonData2.listNames;
                            sonData.listNames.map(it=>{
                                if(it){
                                    if(!sonData2.listNames.includes(it)){//判断是否是区域部门
                                        if(!son_province_list.includes(it)){//去重
                                            son_province_list.push(it)
                                        }
                                    }
                                }
                            })
                        }
                    }
                    if(comment=='省份'){
                        let nameList:any[]=[]
                        if(groupName.includes('区域')){//区域负责人
                            nameList=sonData2.listNames;
                        }else if(groupName.includes('模块')){ //模块负责人
                            nameList=son_province_list
                        }else if(groupName.includes('全国')){//全国负责人
                            nameList=manage_data.proNames
                        }
                        if(nameList.length>0){
                            for (let sonDeptindex = 0; sonDeptindex < nameList.length; sonDeptindex++) {
                                let pro = nameList[sonDeptindex];
                                if (!dataCache[pro]) {
                                    dataCache[pro] = {
                                        areaName:pro,
                                        consumerRate:''
                                    }
                                }
                                userList = await visitMonthPlanModel.distinct("userId", { provinceName:pro, comment: 1, deptId: { $in:sonData.list }, userId: { $ne: '' } }); 
                                let consumerRate_area=0;
                                let rate:any=0;
                                if(userList.length>0){
                                    for (let userindex = 0; userindex < userList.length; userindex++) {
                                        let element2 = userList[userindex];
                                        let consumerRate_one_employee = await formDataService.getReachStoreRate_one_employeeDate1ToDate2(element2, date1, date2);
                                        consumerRate_area+=consumerRate_one_employee;
                                    }
                                    rate=(consumerRate_area/userList.length);
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[pro]={
                                    areaName:pro,
                                    consumerRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                    if(comment=='区域'){
                        let areaNameList:any[]=[]
                        if(groupName.includes('模块')){
                            areaNameList= son_area_list
                        }else if(groupName.includes('全国')){
                            areaNameList=manage_data.areaNames
                        }
                        if(areaNameList.length>0){
                            for (let index = 0; index < areaNameList.length; index++) {
                                const element = areaNameList[index];
                                if (!dataCache[element]) {
                                    dataCache[element] = {
                                        areaName:element,
                                        consumerRate:''
                                    }
                                }
                                userList = await visitMonthPlanModel.distinct("userId", {areaName:element, deptId: { $in: sonData.list },"$and":[{userId: { $ne: '' }},{userId: { $ne:null}}] });
                                let consumerRate_area=0;
                                let rate:any=0;
                                if(userList.length>0){
                                    for (let userindex = 0; userindex < userList.length; userindex++) {
                                        let element2 = userList[userindex];
                                        let consumerRate_one_employee = await formDataService.getReachStoreRate_one_employeeDate1ToDate2(element2, date1, date2);
                                        consumerRate_area+=consumerRate_one_employee;
                                    }
                                    rate=(consumerRate_area/userList.length);
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[element]={
                                    areaName:element,
                                    consumerRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                }   
            }
        }
        for (const key in dataCache) {
            if (dataCache.hasOwnProperty(key)) {
                const element = dataCache[key];
                list.push(element)
            }
        }
        if(list.length==0){
            list.push({
                areaName:'',
                reachStoreRate:0
            })
        }
        console.log(list,'list_list_list_list_list_list_list_list_已拜访门店拜访达标率')
        return list;
    }

    //(四)门店拜访进度------报表
    async getVisitStoreSchadule(startDate1: string, endDate1: string, character: string, comment: string, leaderId: string) {
        let list: any[] = [];
        let dateData=await formDataService.getDate(startDate1,endDate1)
        let date1 = dateData.startDate;
        let date2= dateData.endDate;
        let access_token=await dTalkApiUtil.getAccessToken();
        let authority=await formDataService.getAuthrity(leaderId,access_token)  //权限问题
        let groupName=authority.groupName;
        let dataCache: any = []
        let arr=await emplModel.distinct('userId',{})
        //哪些员工有门店
        let empArr:any[]=[];
        if(comment=='个人'||comment=='区域'||comment=='省份'){
            let codeList=await storeInfoModel.distinct('consumerCode',{});
            empArr=await consumerRecoderModel.distinct('userid',{consumerCode:{$in:codeList},comment:1})
        }
        if (groupName.includes('销售')||(!groupName.includes('销售')&&comment=='个人'&&character)) {//销售
            if (comment=='个人') {
                let num3 =parseInt( moment(date1).format('DD'));
                let num4 =parseInt( moment(date2).format('DD'));
                let userId:any = '';
                let dateList=await formDataService.getDate2(num3,num4,date1)//日期
                if(character==''){
                    userId = leaderId;
                }else{
                   userId=character;
                }
                let name:any='';
                let data5=await visitMonthPlanModel.findOne({userId:userId,'$and':[{user:{$ne:null}},{user:{$ne:''}}]})
                if(data5){
                    name=data5.user
                }else{
                    let employeeInfo:any = ''
                    if(userId==leaderId){
                        employeeInfo=authority.leaderInfo
                    }else{
                        employeeInfo = await dTalkApi.getUserDetail(userId,access_token);
                    }
                    if (employeeInfo&&employeeInfo.name) {
                        name=employeeInfo.name
                    }
                }
                
                //哪些日期有员工拜访过门店
                let dateArr=await storeRecoderModel.distinct('planDate',{"$and": [{ planDate: { "$gte": dateData.startDate } }, { planDate: { "$lte": dateData.endDate } }],userId: userId,planType: '门店'})
                if (dateList.length > 0) {
                    for (let index = 0; index < dateList.length; index++) {
                        let date = dateList[index];
                        let consumerRate_:any =0
                        if(empArr.includes(userId)&&dateArr.includes(date)){
                             consumerRate_ = await formDataService.getShop_schedule_one_employeeDate1ToDate2(userId, date, date); 
                        }
                        let consumerRate = (consumerRate_.toFixed(2)-0)*100;
                        dataCache.push({
                            comment: '一天',
                            userId: userId,
                            userName: name,
                            date:date,
                            consumerRate: consumerRate.toFixed(0)
                        })
                    }
                }
            }
        }else{
            let userList: any[] = [];
            if(authority.leaderDepts.length>0){
                let sonData=await formDataService.getsonDept(authority.leaderDepts,true,access_token,arr);
                let userList2=sonData.userIdData
                let son_list2=sonData.list;
                if (comment == '个人') {
                    if(!character){
                        if(userList2.length>0){
                            for (let index = 0; index < userList2.length; index++) {
                                let element2 = userList2[index];
                                let emp=await visitMonthPlanModel.findOne({userId:element2,"$and":[{user:{$ne:''}},{user:{$ne:null}}]})
                                if (!dataCache[emp.user]) {
                                    dataCache[emp.user] = {
                                        areaName:emp.user,
                                        storeSchadule:''
                                    }
                                }
                                let consumerRate_one_employee:any=0;
                                if(empArr.includes(element2)){
                                    consumerRate_one_employee = await formDataService.getShop_schedule_one_employeeDate1ToDate2(element2, date1, date2);
                                }
                                let a=(consumerRate_one_employee.toFixed(2)-0)*100
                                dataCache[emp.user]={
                                    areaName:emp.user,
                                    storeSchadule:a.toFixed(0)
                                }
                            }
                        }
                    }
                }else if (comment == '店铺等级') {
                    let storeTypeList2=await storeInfoModel.distinct("store_classification",{"$and":[{store_classification:{$ne:null}},{store_classification:{$ne:''}}]});
                    //去除数组元素的首尾空格
                    let storeTypeList:any=[]
                    if(storeTypeList2.length>0){
                        storeTypeList2.map(it=>{
                            if(it){
                                let a=it.trim();
                                if(!storeTypeList.includes(a)){
                                    storeTypeList.push(a)
                                }
                            }
                        })
                    }
                    if(storeTypeList.length>0){
                        for (let index = 0; index < storeTypeList.length; index++) {
                            let element = storeTypeList[index];
                            if (!dataCache[element]) {
                                dataCache[element] = {
                                    areaName:element,
                                    storeSchadule:''
                                }
                            }
                            let consumerCodeList = await storeInfoModel.distinct("consumerCode", { store_classification: element,"$and":[{consumerCode:{$ne:null}},{consumerCode:{$ne:''}}]  });
                            userList = await consumerRecoderModel.distinct("userid", { consumerCode: { $in: consumerCodeList }, comment: 1, "$and":[{userid:{$in:userList2}},{userid:{$ne:null}},{userid:{$ne:''}}] })
                            let reachStoreRate_area=0;//一个区域的客户拜访成功率
                            let rate:any=0;
                            if(userList.length>0){
                                for (let userindex = 0; userindex < userList.length; userindex++) {
                                    let element2 = userList[userindex];
                                    let  reachStoreRate_one_employee = await formDataService.getShop_schedule_one_employeeDate1ToDate2(element2, date1, date2);
                                    reachStoreRate_area+=reachStoreRate_one_employee;
                                }
                                rate=(reachStoreRate_area/userList.length);
                            }
                            let a= (rate.toFixed(2)-0)*100
                            dataCache[element]={
                                areaName:element,
                                storeSchadule: a.toFixed(0)
                            } 
                        }
                    }
                }else if (comment == '城市类型') {
                    let arr2=['T2','T3','T1']
                    let cityTypeList=await storeInfoModel.distinct("cityType",{  "$and":[{cityType:{$ne:null}},{cityType:{$ne:''}},{cityType:{$in:arr2}}]});
                    console.log(cityTypeList,'城市类型')
                    if(cityTypeList.length>0){
                        for (let cityindex = 0; cityindex < cityTypeList.length; cityindex++) {
                            let element = cityTypeList[cityindex];
                            if (!dataCache[element]) {
                                dataCache[element] = {
                                    areaName:element,
                                    storeSchadule:''
                                }
                            } 
                            let consumerCodeList = await storeInfoModel.distinct("consumerCode", { cityType: element,  "$and":[{consumerCode:{$ne:null}},{consumerCode:{$ne:''}}]  });
                            userList = await consumerRecoderModel.distinct("userid", { consumerCode: { $in: consumerCodeList }, comment: 1, "$and":[{userid:{$in:userList2}},{userid:{$ne:null}},{userid:{$ne:''}}] })
                            let storeSchadule_total=0;//门店拜访进度
                            for (let userindex = 0; userindex < userList.length; userindex++) {
                                let element2 = userList[userindex];
                               let shop_schedule_one_employee = await formDataService.getShop_schedule_one_employeeDate1ToDate2(element2, date1, date2);
                               storeSchadule_total += shop_schedule_one_employee;
                            }
                            let rate:any=0;
                            if(userList.length>0){
                                rate=(storeSchadule_total/userList.length);
                            }else{
                                rate=0
                            }
                            let a= (rate.toFixed(2)-0)*100
                            dataCache[element]={
                                areaName:element,
                                storeSchadule: a.toFixed(0)
                            } 
                        }
                    } 
                }else{
                    let sonDept:any=[]
                    let sonData2:any={}
                    if(groupName.includes('区域')||groupName.includes('模块')){
                        sonData2=await formDataService.getsonDept(authority.leaderDepts,false,access_token,arr)
                    }
                    let manage_data:any={}
                    if(groupName.includes('全国')){
                        manage_data=await addNewService.get_model_area_pro_list(access_token);
                    }
                    let son_area_list:any[]=[]//区域部门名称列表
                    let son_province_list:any[]=[]//省份部门名称列表
                    if(groupName.includes('模块')){
                        if(sonData2.listNames.length==0){
                            son_area_list=[];
                            son_province_list=[];
                        }else if(sonData.listNames.length==sonData2.listNames.length&&sonData2.listNames.length>0){
                            son_province_list=[];
                            son_area_list=sonData2.listNames;
                        }else if(sonData.listNames.length !=sonData2.listNames.length&&sonData2.listNames.length>0){
                            son_area_list=sonData2.listNames;
                            sonData.listNames.map(it=>{
                                if(it){
                                    if(!sonData2.listNames.includes(it)){//判断是否是区域部门
                                        if(!son_province_list.includes(it)){//去重
                                            son_province_list.push(it)
                                        }
                                    }
                                }
                            })
                        }
                    }
                    if (comment== '区域') {
                        let areaNameList:any[]=[]
                        if(groupName.includes('模块')){
                            areaNameList= son_area_list
                        }else if(groupName.includes('全国')){
                            areaNameList=await visitMonthPlanModel.distinct("areaName",{areaName:{$in:manage_data.areaNames},comment:1,"$and":[{areaName:{$ne:null}},{areaName:{$ne:''}}]})
                        }
                        if(areaNameList.length>0){
                            for (let index = 0; index < areaNameList.length; index++) {
                                const element = areaNameList[index];
                                if (!dataCache[element]) {
                                    dataCache[element] = {
                                        areaName:element,
                                        storeSchadule:''
                                    }
                                }
                                userList = await visitMonthPlanModel.distinct("userId", {areaName:element, deptId: { $in: son_list2 },"$and":[{userId: { $ne: '' }},{userId: { $ne:null}}] });
                                let storeSchadule=0;//门店拜访进度
                                let rate:any=0;
                                if(userList.length>0){
                                    for (let userindex = 0; userindex < userList.length; userindex++) {
                                        let element2 = userList[userindex];
                                        let consumerRate_one_employee:any=0;
                                        if(empArr.includes(element2)){
                                            consumerRate_one_employee = await formDataService.getShop_schedule_one_employeeDate1ToDate2(element2, date1, date2);
                                        }
                                        storeSchadule+=consumerRate_one_employee;
                                    }
                                    rate=(storeSchadule/userList.length);
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[element]={
                                    areaName:element,
                                    storeSchadule:a.toFixed(0)
                                }
                            }
                        }
                    }
                    if (comment == '省份') {
                        let provinceNameList:any[]=[]
                        if(groupName.includes('模块')){
                            provinceNameList=son_province_list;
                        }else if(groupName.includes('全国')){
                            //provinceNameList=manage_data.proNames;
                            provinceNameList=await visitMonthPlanModel.distinct("provinceName",{provinceName:{$in:manage_data.proNames},comment:1,"$and":[{provinceName:{$ne:null}},{provinceName:{$ne:''}}]})
                        }else if(groupName.includes('区域')){
                            provinceNameList=sonData2.listNames;
                        }
                        if(provinceNameList.length>0){
                            for (let sonDeptindex = 0; sonDeptindex < provinceNameList.length; sonDeptindex++) {
                                let pro = provinceNameList[sonDeptindex];
                                if (!dataCache[pro]) {
                                    dataCache[pro] = {
                                        areaName:pro,
                                        storeSchadule:''
                                    }
                                }
                                userList = await visitMonthPlanModel.distinct("userId", { provinceName:pro, comment: 1, deptId: { $in:son_list2 }, userId: { $ne: '' } }); 
                                let consumerRate_area=0;
                                let rate:any=0;
                                if(userList.length>0){
                                    for (let userindex = 0; userindex < userList.length; userindex++) {
                                        let element2 = userList[userindex];
                                        let consumerRate_one_employee:any=0;
                                        if(empArr.includes(element2)){
                                            consumerRate_one_employee = await formDataService.getShop_schedule_one_employeeDate1ToDate2(element2, date1, date2);
                                        }
                                        consumerRate_area+=consumerRate_one_employee;
                                    }
                                    rate=(consumerRate_area/userList.length);
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[pro]={
                                    areaName:pro,
                                    storeSchadule:a.toFixed(0)
                                }
                            }
                        } 
                    }  
                }
            }
        } 
        for (const key in dataCache) {
            if (dataCache.hasOwnProperty(key)) {
                const element = dataCache[key];
                list.push(element)
            }
        }
        if(list.length==0){
            list.push({
                areaName:'',
                storeSchadule:0
            })
        }
        console.log(list,'list_list_list_list_list_list_list_list_门店拜访进度')
        return list;
    }
    
    //(五)签到率------报表
    async getCheckInRate(startDate1: string, endDate1: string, character: string, comment: string, leaderId:string) {
        let list: any[] = [];
        let dateData=await formDataService.getDate(startDate1,endDate1)
        let date1 = dateData.startDate;
        let date2= dateData.endDate;
        let access_token=await dTalkApiUtil.getAccessToken();
        let authority=await formDataService.getAuthrity(leaderId,access_token) //权限问题
        let groupName=authority.groupName;
        let leaderDepts = authority.leaderDepts
        let dataCache: any = []
        let arr=await emplModel.distinct('userId',{})
        let today=moment().format('YYYY-MM-DD');
        if (groupName.includes('销售')||(!groupName.includes('销售')&&comment=='个人'&&character)) {//销售
            if (comment=='个人') {
                let userId:any = '';
                let num3 =parseInt( moment(date1).format('DD'));
                let num4 =parseInt( moment(date2).format('DD'));
                let dateList=await formDataService.getDate2(num3,num4,date1)//日期
                if(character==''){
                    userId = leaderId;
                }else{
                   userId=character;
                }
                let name:any='';
                let data5=await visitMonthPlanModel.findOne({userId:userId,'$and':[{user:{$ne:null}},{user:{$ne:''}}]})
                if(data5){
                    name=data5.user
                }else{
                    let employeeInfo:any = ''
                    if(userId==leaderId){
                        employeeInfo=authority.leaderInfo
                    }else{
                        employeeInfo = await dTalkApi.getUserDetail(userId,access_token);
                    }
                    if (employeeInfo&&employeeInfo.name) {
                        name=employeeInfo.name
                    }
                }
                if (dateList.length > 0) {
                    for (let index = 0; index < dateList.length; index++) {
                        let date = dateList[index];
                        let consumerRate_:any =0;
                        if(date==today){
                            consumerRate_ = await formDataService.getCheckInRate_one_employeeDate1ToDate2(userId, date, date);
                        }else{
                            let data_it=await excelExportModel.findOne({userId:userId,date_:date});
                            if(data_it){
                                consumerRate_=parseFloat(data_it.checkInRate)
                            }
                        }
                        let consumerRate = (consumerRate_.toFixed(2)-0)*100;
                        dataCache.push({
                            comment: '一天',
                            userId: userId,
                            userName: name,
                            date:date,
                            consumerRate: consumerRate.toFixed(0)
                        })
                    }
                }
            }
        }else{
            let userList: any[] = [];
            if(leaderDepts.length>0){
                let sonDept:any=[]
                let sonData=await formDataService.getsonDept(leaderDepts,true,access_token,arr);
                let userList2=sonData.userIdData;
                let son_list2=sonData.list;
                if (comment == '个人') {
                    if(!character){
                        if(userList2.length>0){
                            for (let index = 0; index < userList2.length; index++) {
                                let element2 = userList2[index];
                                let emp=await visitMonthPlanModel.findOne({userId:element2,"$and":[{user:{$ne:''}},{user:{$ne:null}}]})
                                if (!dataCache[emp.user]) {
                                    dataCache[emp.user] = {
                                        areaName:emp.user,
                                        checkInRate:''
                                    }
                                }
                                let consumerRate_one_employee=0;
                                //consumerRate_one_employee = await formDataService.getCheckInRate_one_employeeDate1ToDate2(element2, date1, date2);
                                if(date2==today){
                                    consumerRate_one_employee = await formDataService.getCheckInRate_one_employeeDate1ToDate2(element2, date1, date2);
                                }else{
                                    let num_date_plan=0;
                                    let num_checkIn=0;
                                    let data_9=await excelExportModel.find({userId:element2,"$and":[{date_:{$gte:date1}},{date_:{$lte:date2}}]});
                                    if(data_9.length>0){
                                        data_9.map(it=>{
                                            if(it){
                                                if(it.visitCount_plan>0){
                                                    num_date_plan+=1;
                                                }
                                                num_checkIn+=it.actuall_checkIn;
                                            }
                                        })
                                    }
                                    if(num_date_plan==0){
                                        consumerRate_one_employee=0;
                                    }else{
                                        consumerRate_one_employee=num_checkIn/num_date_plan;
                                    } 
                                }
                                let rate:any=consumerRate_one_employee
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[emp.user]={
                                    areaName:emp.user,
                                    checkInRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                }else{
                    let sonData2:any={}
                    if(groupName.includes('区域')||groupName.includes('模块')){
                        sonData2=await formDataService.getsonDept(leaderDepts,false,access_token,arr)
                    }
                    let manage_data:any={}
                    if(groupName.includes('全国')){
                        manage_data=await addNewService.get_model_area_pro_list(access_token);
                    }
                    let son_area_list:any[]=[]//区域部门名称列表
                    let son_province_list:any[]=[]//省份部门名称列表
                    if(groupName.includes('模块')){
                        if(sonData2.listNames.length==0){
                            son_area_list=[];
                            son_province_list=[];
                        }else if(sonData.listNames.length==sonData2.listNames.length&&sonData2.listNames.length>0){
                            son_province_list=[];
                            son_area_list=sonData2.listNames;
                        }else if(sonData.listNames.length !=sonData2.listNames.length&&sonData2.listNames.length>0){
                            son_area_list=sonData2.listNames;
                            sonData.listNames.map(it=>{
                                if(it){
                                    if(!sonData2.listNames.includes(it)){//判断是否是区域部门
                                        if(!son_province_list.includes(it)){//去重
                                            son_province_list.push(it)
                                        }
                                    }
                                }
                            })
                        }
                    }
                    if (comment== '区域') {
                        let areaNameList:any[]=[]
                        if(groupName.includes('模块')){
                            areaNameList= son_area_list
                        }else if(groupName.includes('全国')){
                            areaNameList=await visitMonthPlanModel.distinct("areaName",{areaName:{$in:manage_data.areaNames},comment:1,"$and":[{areaName:{$ne:null}},{areaName:{$ne:''}}]})
                        }
                        if(areaNameList.length>0){
                            for (let index = 0; index < areaNameList.length; index++) {
                                const element = areaNameList[index];
                                if (!dataCache[element]) {
                                    dataCache[element] = {
                                        areaName:element,
                                        checkInRate:''
                                    }
                                }
                                userList = await visitMonthPlanModel.distinct("userId", {areaName:element, deptId: { $in: son_list2 },"$and":[{userId: { $ne: '' }},{userId: { $ne:null}}] });
                                let consumerRate_area=0;//签到率
                                let rate:any=0;
                                if(userList.length>0){
                                    if(date2!=today){
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let element2 = userList[userindex];
                                            let num_date_plan=0;
                                            let num_checkIn=0;
                                            let data_9=await excelExportModel.find({userId:element2,"$and":[{date_:{$gte:date1}},{date_:{$lte:date2}}]});
                                            if(data_9.length>0){
                                                data_9.map(it=>{
                                                    if(it){
                                                        if(it.visitCount_plan>0){
                                                            num_date_plan+=1;
                                                        }
                                                        num_checkIn+=it.actuall_checkIn;
                                                    }
                                                })
                                            }
                                            if(num_date_plan==0){
                                                consumerRate_area+=0;
                                            }else{
                                                consumerRate_area+=(num_checkIn/num_date_plan);
                                            }
                                        }
                                    }else{
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let element2 = userList[userindex];
                                            let consumerRate_one_employee = await formDataService.getCheckInRate_one_employeeDate1ToDate2(element2, date1, date2);
                                            consumerRate_area+=consumerRate_one_employee;
                                        }
                                    }
                                    rate=(consumerRate_area/userList.length);
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[element]={
                                    areaName:element,
                                    checkInRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                    if (comment == '省份') {
                        let provinceNameList:any[]=[]
                        if(groupName.includes('模块')){
                            provinceNameList=son_province_list;
                        }else if(groupName.includes('全国')){
                            provinceNameList=await visitMonthPlanModel.distinct("provinceName",{provinceName:{$in:manage_data.proNames},comment:1,"$and":[{provinceName:{$ne:null}},{provinceName:{$ne:''}}]})
                        }else if(groupName.includes('区域')){
                            provinceNameList=sonData2.listNames;
                        }
                        if(provinceNameList.length>0){
                            for (let sonDeptindex = 0; sonDeptindex < provinceNameList.length; sonDeptindex++) {
                                let pro = provinceNameList[sonDeptindex];
                                if (!dataCache[pro]) {
                                    dataCache[pro] = {
                                        areaName:pro,
                                        checkInRate:''
                                    }
                                }
                                userList = await visitMonthPlanModel.distinct("userId", { provinceName:pro, comment: 1, deptId: { $in:son_list2 }, userId: { $ne: '' } }); 
                                let consumerRate_area=0;//签到率
                                let rate:any=0;
                                if(userList.length>0){
                                    if(date2==today){
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let element2 = userList[userindex];
                                            let consumerRate_one_employee = await formDataService.getCheckInRate_one_employeeDate1ToDate2(element2, date1, date2);
                                            consumerRate_area+=consumerRate_one_employee;
                                        }
                                    }else{
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let element2 = userList[userindex];
                                            let num_date_plan=0;
                                            let num_checkIn=0;
                                            let data_9=await excelExportModel.find({userId:element2,"$and":[{date_:{$gte:date1}},{date_:{$lte:date2}}]});
                                            if(data_9.length>0){
                                                data_9.map(it=>{
                                                    if(it){
                                                        if(it.visitCount_plan>0){
                                                            num_date_plan+=1;
                                                        }
                                                        num_checkIn+=it.actuall_checkIn;
                                                    }
                                                })
                                            }
                                            if(num_date_plan==0){
                                                consumerRate_area+=0;
                                            }else{
                                                consumerRate_area+=(num_checkIn/num_date_plan);
                                            }
                                        } 
                                    }
                                    rate=(consumerRate_area/userList.length);
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[pro]={
                                    areaName:pro,
                                    checkInRate:a.toFixed(0)
                                }
                            }
                        }     
                    }
                }
            }
        } 
        for (const key in dataCache) { //移植dataCache当中的属性到list当中
            if (dataCache.hasOwnProperty(key)) {
                const element = dataCache[key];
                list.push(element)
            }
        }
        if(list.length==0){
            list.push({
                areaName:'',
                checkInRate:0
            })
        }
        console.log(list,'list_list_list_list_list_list_list_list_签到率')
        return list;
    }


    //(六)出差频率------报表
    async getTravelFrequency(startDate1: string, endDate1: string, character: string, comment: string, leaderId: string) {
        let list: any[] = [];  
        let dateData=await formDataService.getDate(startDate1,endDate1)
        let date1 = dateData.startDate;
        let date2= dateData.endDate;
        let access_token=await dTalkApiUtil.getAccessToken();
        let authority=await formDataService.getAuthrity(leaderId,access_token) //权限问题
        let groupName=authority.groupName;
        let leaderDepts = authority.leaderDepts
        let dataCache: any = []
        let arr=await emplModel.distinct('userId',{})
        let today=moment().format('YYYY-MM-DD');
        if (groupName.includes('销售')||(!groupName.includes('销售')&&comment=='个人'&&character)) {//销售
            if (comment=='个人') {
                let userId:any = '';
                let num3 =parseInt( moment(date1).format('DD'));
                let num4 =parseInt( moment(date2).format('DD'));
                let dateList=await formDataService.getDate2(num3,num4,date1)//日期
                if(character==''){
                    userId = leaderId;
                }else{
                   userId=character;
                }
                let name:any='';
                let data5=await visitMonthPlanModel.findOne({userId:userId,'$and':[{user:{$ne:null}},{user:{$ne:''}}]})
                if(data5){
                    name=data5.user
                }else{
                    let employeeInfo:any = ''
                    if(userId==leaderId){
                        employeeInfo=authority.leaderInfo
                    }else{
                        employeeInfo = await dTalkApi.getUserDetail(userId,access_token);
                    }
                    if (employeeInfo&&employeeInfo.name) {
                        name=employeeInfo.name
                    }
                }
                if (dateList.length > 0) {
                    for (let index = 0; index < dateList.length; index++) {
                        let date = dateList[index];
                        let consumerRate_:any = 0
                        if(date==today){
                            consumerRate_=await formDataService.getgetTravelFrequency_oneemployeeDate1ToDate2(userId, date, date);
                        }else{
                            let num_date_plan=0;//这个时间段上班的天数
                            let num_unBasecheck=0;//这个时间段出差的天数
                            let data_9=await excelExportModel.findOne({userId:userId,date_:date});
                            if(data_9){
                                if(data_9.visitCount_plan>0){
                                    num_date_plan=1;
                                }
                                num_unBasecheck=data_9.unBase_check; 
                            }
                            if(num_date_plan>0){
                                consumerRate_=num_unBasecheck/num_date_plan;
                            }
                        }
                        let consumerRate = (consumerRate_.toFixed(2)-0)*100;
                        dataCache.push({
                            comment: '一天',
                            userId: userId,
                            userName: name,
                            date:date,
                            consumerRate: consumerRate.toFixed(0)
                        })
                    }
                }
            }
        }else{
            let userList: any[] = [];
            if(leaderDepts.length>0){
                let sonDept:any=[]
                let sonData=await formDataService.getsonDept(leaderDepts,true,access_token,arr);
                let userList2=sonData.userIdData;
                let son_list2=sonData.list;
                if (comment == '个人') {
                    if(!character){
                        if(userList2.length>0){
                            for (let index = 0; index < userList2.length; index++) {
                                let element2 = userList2[index];
                                let emp=await visitMonthPlanModel.findOne({userId:element2,"$and":[{user:{$ne:''}},{user:{$ne:null}}]})
                                if (!dataCache[emp.user]) {
                                    dataCache[emp.user] = {
                                        areaName:emp.user,
                                        travelFrequency:''
                                    }
                                }
                                let rate:any= 0
                                if(date2==today){
                                    rate= await formDataService.getgetTravelFrequency_oneemployeeDate1ToDate2(element2, date1, date2);
                                }else{
                                    let num_date_plan=0;
                                    let num_unBasecheck=0;
                                    let data_9=await excelExportModel.find({userId:element2,"$and":[{date_:{$gte:date1}},{date_:{$lte:date2}}]});
                                    if(data_9.length>0){
                                        data_9.map(it=>{
                                            if(it){
                                                if(it.visitCount_plan>0){
                                                    num_date_plan+=1;
                                                }
                                                if(it.unBase_check>0){
                                                    num_unBasecheck+=1;
                                                }
                                            }
                                        })
                                    }
                                    if(num_date_plan>0){
                                        rate=num_unBasecheck/num_date_plan;
                                    }
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[emp.user]={
                                    areaName:emp.user,
                                    travelFrequency:a.toFixed(0)
                                }
                            }
                        }
                    }
                }else if (comment == '城市类型') {
                    let arr2=['T2','T3','T1']
                    let cityTypeList=await storeInfoModel.distinct("cityType",{  "$and":[{cityType:{$ne:null}},{cityType:{$ne:''}},{cityType:{$in:arr2}}]});
                    //let cityTypeList=await storeInfoModel.distinct("cityType",{"$and":[{cityType:{$ne:''}},{cityType:{$ne:null}}]});
                    console.log(cityTypeList,'城市类型')
                    if(cityTypeList.length>0){
                        for (let cityindex = 0; cityindex < cityTypeList.length; cityindex++) {
                            let element = cityTypeList[cityindex];
                            if (!dataCache[element]) {
                                dataCache[element] = {
                                    areaName:element,
                                    travelFrequency:''
                                }
                            }
                            let consumerCodeList = await storeInfoModel.distinct("consumerCode", { cityType: element, consumerCode: { $ne:null} });
                            userList = await consumerRecoderModel.distinct("userid", { consumerCode: { $in: consumerCodeList }, comment: 1, "$and":[{userid:{$in:userList2}},{userid:{$ne:''}},{userid:{$ne:null}}] })
                            let travelFrequency_total=0;//出差频率
                            let rate:any=0;
                            if(userList.length>0){
                                for (let userindex = 0; userindex < userList.length; userindex++) {
                                    let element2 = userList[userindex];
                                    let travelFrequency_oneEmployee = await formDataService.getgetTravelFrequency_oneemployeeDate1ToDate2(element2, date1, date2);
                                    travelFrequency_total += travelFrequency_oneEmployee;
                                }
                                rate=(travelFrequency_total/userList.length);
                            }
                            let a= (rate.toFixed(2)-0)*100
                            dataCache[element]={
                                areaName:element,
                                travelFrequency:a.toFixed(0)
                            }
                        }
                    }
                }else{
                    let sonData2:any={}
                    if(groupName.includes('区域')||groupName.includes('模块')){
                        sonData2=await formDataService.getsonDept(leaderDepts,false,access_token,arr)
                    }
                    let manage_data:any={}
                    if(groupName.includes('全国')){
                        manage_data=await addNewService.get_model_area_pro_list(access_token);
                    }
                    let son_area_list:any[]=[]//区域部门名称列表
                    let son_province_list:any[]=[]//省份部门名称列表
                    if(groupName.includes('模块')){
                        if(sonData2.listNames.length==0){
                            son_area_list=[];
                            son_province_list=[];
                        }else if(sonData.listNames.length==sonData2.listNames.length&&sonData2.listNames.length>0){
                            son_province_list=[];
                            son_area_list=sonData2.listNames;
                        }else if(sonData.listNames.length !=sonData2.listNames.length&&sonData2.listNames.length>0){
                            son_area_list=sonData2.listNames;
                            sonData.listNames.map(it=>{
                                if(it){
                                    if(!sonData2.listNames.includes(it)){//判断是否是区域部门
                                        if(!son_province_list.includes(it)){//去重
                                            son_province_list.push(it)
                                        }
                                    }
                                }
                            })
                        }
                    }
                    if (comment== '区域') {
                        let areaNameList:any[]=[]
                        if(groupName.includes('模块')){
                            areaNameList= son_area_list
                        }else if(groupName.includes('全国')){
                            areaNameList=await visitMonthPlanModel.distinct("areaName",{areaName:{$in:manage_data.areaNames},comment:1,"$and":[{areaName:{$ne:null}},{areaName:{$ne:''}}]})
                        }
                        if(areaNameList.length>0){
                            for (let index = 0; index < areaNameList.length; index++) {
                                const element = areaNameList[index];
                                if (!dataCache[element]) {
                                    dataCache[element] = {
                                        areaName:element,
                                        travelFrequency:''
                                    }
                                }
                                userList = await visitMonthPlanModel.distinct("userId", {areaName:element, deptId: { $in: son_list2 },"$and":[{userId: { $ne: '' }},{userId: { $ne:null}}] });
                                let consumerRate_area=0;//出差频率
                                let rate:any=0;
                                if(userList.length>0){
                                    if(date2==today){
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let element2 = userList[userindex];
                                            let consumerRate_one_employee = await formDataService.getgetTravelFrequency_oneemployeeDate1ToDate2(element2, date1, date2);
                                            consumerRate_area+=consumerRate_one_employee;
                                        }
                                    }else{
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let element2 = userList[userindex];
                                            let num_date_plan=0;
                                            let num_unBasecheck=0;
                                            let data_9=await excelExportModel.find({userId:element2,"$and":[{date_:{$gte:date1}},{date_:{$lte:date2}}]});
                                            if(data_9.length>0){
                                                data_9.map(it=>{
                                                    if(it){
                                                        if(it.visitCount_plan>0){
                                                            num_date_plan+=1;
                                                        }
                                                        if(it.unBase_check>0){
                                                            num_unBasecheck+=1;
                                                        }
                                                        
                                                    }
                                                })
                                            }
                                            if(num_date_plan>0){
                                                consumerRate_area+=(num_unBasecheck/num_date_plan);
                                            }else{
                                                consumerRate_area+=0;
                                            }
                                        } 
                                    }
                                    rate=(consumerRate_area/userList.length);
                                }
                                let a=(rate.toFixed(2)-0)*100;
                                dataCache[element]={
                                    areaName:element,
                                    travelFrequency:a.toFixed(0)
                                }
                            }
                        }
                    }
                    if (comment == '省份') {
                        let provinceNameList:any[]=[]
                        if(groupName.includes('模块')){
                            provinceNameList=son_province_list;
                        }else if(groupName.includes('全国')){
                            provinceNameList=await visitMonthPlanModel.distinct("provinceName",{provinceName:{$in:manage_data.proNames},comment:1,"$and":[{provinceName:{$ne:null}},{provinceName:{$ne:''}}]})
                        }else if(groupName.includes('区域')){
                            provinceNameList=sonData2.listNames;
                        }
                        if(provinceNameList.length>0){
                            for (let sonDeptindex = 0;  sonDeptindex< provinceNameList.length; sonDeptindex++) {
                                let pro = provinceNameList[sonDeptindex];
                                if (!dataCache[pro]) {
                                    dataCache[pro] = {
                                        areaName:pro,
                                        travelFrequency:''
                                    }
                                }
                                userList = await visitMonthPlanModel.distinct("userId", {provinceName:pro, comment: 1, deptId: { $in:son_list2 }, userId: { $ne: '' } }); 
                                let consumerRate_area=0;//出差频率
                                let rate:any=0;
                                if(userList.length>0){
                                    if(date2==today){
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let element2 = userList[userindex];
                                            let consumerRate_one_employee = await formDataService.getgetTravelFrequency_oneemployeeDate1ToDate2(element2, date1, date2);
                                            consumerRate_area+=consumerRate_one_employee;
                                        }
                                    }else{
                                        for (let userindex = 0; userindex < userList.length; userindex++) {
                                            let element2 = userList[userindex];
                                            let num_date_plan=0;
                                            let num_unBasecheck=0;
                                            let data_9=await excelExportModel.find({userId:element2,"$and":[{date_:{$gte:date1}},{date_:{$lte:date2}}]});
                                            if(data_9.length>0){
                                                data_9.map(it=>{
                                                    if(it){
                                                        if(it.visitCount_plan>0){
                                                            num_date_plan+=1;
                                                        }
                                                        if(it.unBase_check>0){
                                                            num_unBasecheck+=1;
                                                        }
                                                    }
                                                })
                                            }
                                            if(num_date_plan>0){
                                                consumerRate_area+=(num_unBasecheck/num_date_plan);
                                            }else{
                                                consumerRate_area+=0;
                                            }
                                        } 
                                    }
                                    rate=(consumerRate_area/userList.length);
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[pro]={
                                    areaName:pro,
                                    travelFrequency:a.toFixed(0)
                                }
                            }
                        } 
                    }        
                }
            }
        }
        for (const key in dataCache) { 
            if (dataCache.hasOwnProperty(key)) {
                const element = dataCache[key];
                list.push(element)
            }
        }
        if(list.length==0){
            list.push({
                areaName:'',
                travelFrequency:0
            })
        }
        console.log(list,'list_list_list_list_list_list_list_list_出差频率')
        return list;
    }

}
let reportForm = new ReportFormService();
export default reportForm;